import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.font_manager
from pyod.models.abod import ABOD

from pyod.utils.data import generate_data,get_outliers_inliers

#生成数据：
# 生成二维随机数据
X_train, Y_train = generate_data(n_train=200,train_only=True, n_features=2)

print (X_train)
print ("===============")
print (Y_train)

# # 拆分出异常数据和正常数据
# x_outliers, x_inliers = get_outliers_inliers(X_train,Y_train)
#
# # 绘制生成的数据图
# F1 = X_train[:,[0]].reshape(-1,1)
# F2 = X_train[:,[1]].reshape(-1,1)
# plt.scatter(F1,F2)
# plt.xlabel('F1')
# plt.ylabel('F2')
# plt.show()

'''
#2.1.3 abod算法训练

outlier_fraction = 0.1#异常值比例
abod = ABOD(contamination=outlier_fraction)#生成模型
abod.fit(X_train)#训练模型
score = abod.decision_scores_# 注意异常得分是负的
score = score * -1
print (score.shape)


#预测结果
y_pred = abod.predict(X_train)# 预测训练样本的标签
from sklearn.metrics import classification_report
print(classification_report(y_true=Y_train,y_pred=y_pred))



#绘制热力图
n_inliers = len(x_inliers)
n_outliers = len(x_outliers)
#生成热力图的坐标点
xx , yy = np.meshgrid(np.linspace(-10, 10, 200), np.linspace(-10, 10, 200))
# 根据百分比生成
threshold = -abod.threshold_

# 得到每个坐标点的异常值得分
Z = abod.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.figure(figsize=(10, 10))
#将正常样本区域绘制成蓝色
plt.contourf(xx, yy, Z, levels = np.linspace(Z.min(), threshold, 10),cmap=plt.cm.Blues_r)
#绘制决策曲线
a = plt.contour(xx, yy, Z, levels=[threshold],linewidths=2, colors='red')
#将异常样本区域绘制成橘黄色
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()],colors='orange')
#绘制正常点（白色）
b = plt.scatter(X_train[:-n_outliers, 0], X_train[:-n_outliers, 1], c='white',s=20, edgecolor='k')
# 绘制异常点（黑色）
c = plt.scatter(X_train[-n_outliers:, 0], X_train[-n_outliers:, 1], c='black',s=20, edgecolor='k')
plt.axis('tight')

plt.legend(
    [a.collections[0], b, c],
    ['learned decision function', 'true inliers', 'true outliers'],
    prop=matplotlib.font_manager.FontProperties(size=10),
    loc='lower right')

plt.title('ADOB')
plt.xlim((-10, 10))
plt.ylim((-10, 10))
plt.show()
'''